<template>
  <a-form :form="form">
    <div class="drawer">
      <div class="drawer-item">
        <div class="drawer-label"><label>{{ $t('task.topic') }}</label></div>
        <div class="drawer-control">
          <a-input v-model="data.topic" :allow-clear="true" :placeholder="$t('enter.please')" />
        </div>
      </div>
      <div class="drawer-item">
        <div class="drawer-label"><label>{{ $t('task.tag') }}</label></div>
        <div class="drawer-control">
          <a-form-item>
            <a-input v-model="data.tag" :allow-clear="true" :placeholder="$t('enter.please')" />
          </a-form-item>
        </div>
      </div>
      <div class="drawer-item">
        <div class="drawer-label"><label>{{ $t('message.body') }}</label></div>
        <div class="drawer-control">
          <a-form-item>
            <a-textarea rows="6" v-model="data.message" :allow-clear="true" :placeholder="$t('message.body.placeholder')" />
          </a-form-item>
        </div>
      </div>
      <div class="drawer-item">
        <div class="drawer-label">
          <label>{{ $t('message.delay.seconds') }}</label>
        </div>
        <div class="drawer-control">
          <a-input
            type="number"
            min="0"
            max="86400"
            v-model="data.delay_seconds"
            :placeholder="$t('enter.please')"
            :suffix="$t('unit.second')"
          />
          <p v-html="$t('message.delay.seconds.description', {seconds: data.delay_seconds})" />
        </div>
      </div>
      <div class="drawer-button">
        <a-form-item>
          <a-button v-if="loading" type="primary" :disabled="true">{{ $t('action.publish.requesting') }}</a-button>
          <a-button v-else type="primary" @click="submit">{{ $t('action.publish') }}</a-button>
          <a-button type="default" @click="close">{{ $t('action.close') }}</a-button>
        </a-form-item>
      </div>
    </div>
  </a-form>
</template>

<script>
import { publishMessage } from '@/api/v1'

export default {
  data () {
    return {
      data: { topic: '', tag: '', message_body: '', delay_seconds: 0 },
      form: this.$form.createForm(this),
      loading: false
    }
  },
  methods: {
    close () { this.$emit('update:close') },
    submit () {
      this.loading = true
      publishMessage(this.data, () => {
        this.loading = false
        this.$emit('update:submit')
      }, (err) => {
        this.loading = false
        this.$message.error(err)
      })
    }
  },
  mounted () { this.data = this.origin },
  name: 'PublishServlets',
  props: { origin: { type: Object, required: true } },
  watch: { origin: { handler (data) { this.data = data } } }
}
</script>
